package com.sljy.hzk.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.sljy.hzk.R;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.DangerDatabaseEntity;
import com.sljy.hzk.entity.DetectionHistroyEntity;
import com.sljy.hzk.entity.TaskEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.DetectionService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.DangerDao;
import com.sljy.hzk.ui.detection.DetectionFillInActivity__JumpCenter;
import com.sljy.hzk.ui.detection.DetectionMainActivity;
import com.sljy.hzk.ui.fragment.lazyfragment.LazyFragment;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.view.MarginItemDecoration;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;

/**
 * Created  on 2018/7/11 0011
 *
 * @author 唐开阔
 * @describe
 */
public class DetectionFragment extends LazyFragment {
    @BindView(R.id.recycer)
    RecyclerView recycerView;
    public int type;
    public static final int TYPE_UNFINSH = 1;
    public static final int TYPE_FINSH = 2;
    DangerDao dangerDao;
    BaseQuickAdapter adapter;
    List<DangerDatabaseEntity> databaseEntityList;//未完成
    List<DetectionHistroyEntity> finishDataList;//已完成
    UserEntity userEntity;
    DetectionMainActivity baseActivity;
    /**
     * 1:已上传，2：未上传
     * @param type
     * @return
     */
    public static DetectionFragment get(int type) {
        DetectionFragment detectionFragment = new DetectionFragment();
        detectionFragment.type = type;
        return detectionFragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        baseActivity = (DetectionMainActivity) activity;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userEntity =UserInfo.getUserInfo();
        RxEventProcessor.get().bind(this);
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_detection;
    }

    @Override
    protected void onRealViewLoaded(View view) {
        dangerDao = AppDataBase.getInstance().getDangerDao();
        if(databaseEntityList == null)
            databaseEntityList = new ArrayList<DangerDatabaseEntity>();
        if(type == TYPE_FINSH){
            finishDataList = baseActivity.getFinishData();
            Gson json = new Gson();
            List<DangerDatabaseEntity> sortList = new ArrayList<DangerDatabaseEntity>();
            for(DetectionHistroyEntity list : finishDataList){
                DangerDatabaseEntity d = new DangerDatabaseEntity(true,list.getRecordName(),0,list.partitionName,list.time, json.toJson(list.value),list.time,String.valueOf(UserInfo.getUserInfo().getUserId()) );
                sortList.add(d);
            }
            Collections.sort(sortList, new Comparator<DangerDatabaseEntity>() {
                @Override
                public int compare(DangerDatabaseEntity o1, DangerDatabaseEntity o2) {
                    int i = TimeUtils.compare_date(o2.getTime(), o1.getTime()) ;
                    return i;
                }
            });
            databaseEntityList = sortList;
        }else{
            databaseEntityList = dangerDao.getById(String.valueOf(userEntity.getUserId()));
        }
        recycerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recycerView.addItemDecoration(new MarginItemDecoration(20));
        adapter = new BaseQuickAdapter<DangerDatabaseEntity, BaseViewHolder>(R.layout.item_detevtion, databaseEntityList) {
            @Override
            protected void convert(BaseViewHolder helper, final DangerDatabaseEntity item) {
                helper.setText(R.id.tv_title,item.getRecordName());
                helper.getView(R.id.tv_finsh).setVisibility(item.isFinsh()?View.VISIBLE:View.GONE);
                helper.getView(R.id.tv_up).setVisibility(!item.isFinsh()?View.VISIBLE:View.GONE);
                helper.setText(R.id.tv_time,item.getTime());
                helper.setText(R.id.tv_pos,item.getPosName());
                helper.getView(R.id.tv_up).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        upData(item,helper.getAdapterPosition());
                    }
                });
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DangerDatabaseEntity item = databaseEntityList.get(position);
                DetectionFillInActivity__JumpCenter
                        .builder(getActivity())
                        .setIsFromLocal(true)
                        .setDatabaseEntity(item)
                        .create()
                        .go();
            }
        });
        recycerView.setAdapter(adapter);
    }

    /**
     * 上传单条数据
     * @param item
     * @param adapterPosition
     */
    private void upData(DangerDatabaseEntity item, int adapterPosition) {
        HttpHeper.get().create(DetectionService.class). submit(userEntity.getUserId(),item.getRecordName(),item.getpId(),userEntity.getComPId(),item.getDataJson())
                .compose(baseActivity.getThread())
                .compose(baseActivity.bindUntilEvent(ActivityEvent.DESTROY))
                .doOnNext(objectCommonResult -> {
//                        item.setTime(TimeUtils.getNowNyr());
//                        item.setFinsh(true);
//                        dangerDao.update(item);
//                    RxEventProcessor.get().post("UpOne",item.getId());

                })
                .subscribe(new BaseCallBack<Object>(baseActivity) {
                    @Override
                    public void onCallBackSuccess(Object data) {
                        showToast("上传成功");
                        dangerDao.delete(item);
                        databaseEntityList.remove(adapterPosition);
                        adapter.notifyItemRemoved(adapterPosition);
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });
    }

    @Recipient(tag = "DetectionDataHaveChange")
    public void notifyDataSetChanged(){
        if(type !=  TYPE_FINSH){
            databaseEntityList.clear();
            databaseEntityList.addAll(dangerDao.get(type == TYPE_FINSH));
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 上传成功一条数据这边改变
     */
    @Recipient(tag = "UpOne")
    public void upOne(int id){
        if (type == TYPE_FINSH ){
            databaseEntityList.add(dangerDao.getById(id));
            adapter.notifyItemInserted(databaseEntityList.size() - 1);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);

    }
}
